package org.fruitrecognitionbasedonai.fruitrecognitionbasedonai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.fruitrecognitionbasedonai.fruitrecognitionbasedonai.entity.Record;
import org.fruitrecognitionbasedonai.fruitrecognitionbasedonai.entity.UserRecord;
import org.fruitrecognitionbasedonai.fruitrecognitionbasedonai.mapper.RecordMapper;
import org.fruitrecognitionbasedonai.fruitrecognitionbasedonai.mapper.UserRecordMapper;
import org.fruitrecognitionbasedonai.fruitrecognitionbasedonai.service.IRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Re
 * @Date: 2021/6/19 23:53
 */
@Service
public class RecordServiceImpl implements IRecordService {
    @Autowired
    protected UserRecordMapper userRecordMapper;
    @Autowired
    protected RecordMapper recordMapper;
    @Override
    public boolean insert(Record record) {
        return recordMapper.insert(record) == 1;
    }

    @Override
    public boolean deleteById(Integer recordId) {
        return recordMapper.deleteById(recordId) == 1;
    }

    @Override
    public boolean deleteList(Integer userId) {
        LambdaQueryWrapper<UserRecord> queryWrapper = new LambdaQueryWrapper<>();
        List<UserRecord> userRecordList = userRecordMapper.selectList(queryWrapper.eq(UserRecord::getUserId,userId));
        boolean flag = true;
        for (UserRecord userRecord :userRecordList) {
            if (recordMapper.deleteById(userRecord.getRecordId()) != 1) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    @Override
    public List<Record> selectAll() {
        return recordMapper.selectList(null);
    }

    @Override
    public Record selectById(Integer recordId) {
        return recordMapper.selectById(recordId);
    }

    @Override
    public Integer selectId(Record record) {
        LambdaQueryWrapper<Record> queryWrapper = new LambdaQueryWrapper<Record>()
                .eq(Record::getPictureUrl,record.getPictureUrl())
                .eq(Record::getName,record.getName())
                .eq(Record::getScore,record.getScore())
                .eq(Record::getRequestTime,record.getRequestTime());
        List<Record> records = recordMapper.selectList(queryWrapper);
        return records.get(0).getId();
    }

    @Override
    public List<Record> selectByUserId(Integer userId) {
        LambdaQueryWrapper<UserRecord> queryWrapper = new LambdaQueryWrapper<>();
        List<UserRecord> userRecordList = userRecordMapper.selectList(queryWrapper.eq(UserRecord::getUserId,userId));
        List<Record> recordList = new ArrayList<>();
        for (UserRecord userRecord:userRecordList) {
            recordList.add(recordMapper.selectById(userRecord.getRecordId()));
        }
        return recordList;
    }
}
